package models

import (
	"gorm.io/gorm"
	"time"
)

type Org struct {
	gorm.Model
	Name     string `json:"name" bson:"name" gorm:"uniqueIndex"`
	Email    string `json:"email" bson:"email"`
	INN      string `json:"inn" bson:"inn"`
	OGRN     string `json:"ogrn" bson:"ogrn"`
	Phone    string `json:"phone" bson:"phone"`
	Address  string `json:"address" bson:"address"`
	Director string `json:"director" bson:"director"`
}

// Saves a user to the database
func (org *Org) Save() (*Org, error) {
	err := Database.Model(&org).Create(&org).Error
	if err != nil {
		return &Org{}, err
	}
	return org, nil
}

// Fetches all orgs from the database
func FetchAllOrgs() (*[]Org, error) {
	var orgs []Org

	err := Database.Find(&orgs).Error
	if err != nil {
		return &[]Org{}, err
	}
	return &orgs, nil
}

// Fetches a user from the database
func FetchOrg(id string) (*Org, error) {
	var org Org
	err := Database.Where("id = ?", id).First(&org).Error
	if err != nil {
		return &Org{}, err
	}
	return &org, nil
}

// Updates a user in the database
func (org *Org) UpdateOrg(id string) (*Org, error) {
	err := Database.Model(&Org{}).Where("id = ?", id).Updates(org).Error
	if err != nil {
		return &Org{}, err
	}
	return org, nil
}

// Deletes a user from the database
func DeleteOrg(id string) error {
	err := Database.Model(&Org{}).Where("id = ?", id).Delete(&Org{}).Error
	if err != nil {
		return err
	}
	return nil
}

func (org *Org) BeforeSave(tx *gorm.DB) (err error) {
    org.UpdatedAt = time.Now()
    return nil
}

func (org *Org) BeforeCreate(tx *gorm.DB) (err error) {
    org.CreatedAt = time.Now()
    return nil
}
